﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Spore.Utils
{
   public class ThreadWorkManager:ThreadWorkManagerBase
    {
        /// <summary>
        ///   高优先级的工作队列
        /// </summary>
        protected Queue<ThreadWorkExecuter> HeighPriorityLevel;
        /// <summary>
        ///  普通优先级的工作队列
        /// </summary>
        protected Queue<ThreadWorkExecuter> CommonPriorityLevel;
        /// <summary>
        /// 低优先级的工作队列
        /// </summary>
        protected Queue<ThreadWorkExecuter> LowPriorityLevel;

        protected List<ThreadWorkExecuter> buffer;

        private object obj_lock= new object();

        public ThreadWorkManager()
        {
            this.HeighPriorityLevel = new Queue<ThreadWorkExecuter>();
            this.CommonPriorityLevel = new Queue<ThreadWorkExecuter>();
            this.LowPriorityLevel = new Queue<ThreadWorkExecuter>();
            this.buffer = new List<ThreadWorkExecuter>();
        }

        protected override ThreadWorkExecuter GetWorkExecuter()
        {
            lock (obj_lock)
            {
                if (this.buffer.Count > 0)
                {
                    foreach (var executer in this.buffer)
                    {
                        switch (executer.WorkItem.Priority)
                        {
                            case ThreadWorkPriority.Common:
                                this.CommonPriorityLevel.Enqueue(executer);
                                break;
                            case ThreadWorkPriority.High:
                                this.HeighPriorityLevel.Enqueue(executer);
                                break;
                            case ThreadWorkPriority.Low:
                                this.LowPriorityLevel.Enqueue(executer);
                                break;
                        }
                    }
                    buffer.Clear();
                }
                if (HeighPriorityLevel.Count > 0)
                    return HeighPriorityLevel.Dequeue();
                if (CommonPriorityLevel.Count > 0)
                    return CommonPriorityLevel.Dequeue();
                if (LowPriorityLevel.Count > 0)
                    return LowPriorityLevel.Dequeue();
                return null;
            }
        }

        public void AddWorkItem(ThreadWorkItem workItem)
        {
            ThreadWorkExecuter executer = new ThreadWorkExecuter(workItem);
            lock (obj_lock)
            {
                this.buffer.Add(executer);
            }
            this.waitResetEvent.Set();
        }
    }
}
